﻿using MediatR;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Read.Command.RBAC;

namespace RBAC.Api.Read.CommandHandler.RBAC
{
    public class GetPressionCommandHandler : IRequestHandler<GetPressionCommand, APIResult<APIPagin<Permission>>>
    {
        private readonly IBaseRepositry<Permission> baseRepositry;

        public GetPressionCommandHandler(IBaseRepositry<Permission> baseRepositry)
        {
            this.baseRepositry = baseRepositry;
        }
        /// <summary>
        /// 获取权限
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回结果</returns>
        public Task<APIResult<APIPagin<Permission>>> Handle(GetPressionCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPagin<Permission>> result = new APIResult<APIPagin<Permission>>();
            result.Code = ResultCode.Success;
            result.Message = "成功";

            var list = baseRepositry.GetAll();
            if (!string.IsNullOrEmpty(request.PermissionName))
            {
                list = list.Where(x => x.PermissionName.Contains(request.PermissionName));
            }
            var totalCount = list.Count();
            var page = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            list = list.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPagin<Permission> res = new APIPagin<Permission>()
            {
                TotaleCount = totalCount,
                PageCount = page,
                List = list.ToList()
            };

            result.Data = res;

            return Task.FromResult(result);
        }
    }
}
